package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.Util.History;
import com.mtnz.njk.Util.MapDistance;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.ResearchListModel;
import com.mtnz.njk.model.ResearchModel;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;
/*
......................我佛慈悲......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG...................
 */

/**
 * @Description: 研究院帖子业务层
 * @Author: ZPX
 * @CreateDate: 2019/7/12 9:25
 * @Version: 1.0
 */
@Service
public class ResearchService {

    //帖子
    @Autowired
    ResearchMapper researchMapper;

    //帖子图
    @Autowired
    ResearchImgMapper researchImgMapper;

    //赞
    @Autowired
    PraiseResearchMapper praiseResearchMapper;

    //用户
    @Autowired
    CommunityUserMapper communityUserMapper;

    @Autowired
    CommunityUserInfoMapper communityUserInfoMapper;

    //用户任务
    @Autowired
    UserTaskMapperr userTaskMapperr;

    @Autowired
    UserTaskCountMapper userTaskCountMapper;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    //商品
    @Autowired
    ResearchProductMapper researchProductMapper;

    //提问
    @Autowired
    AskMapper askMapper;

    @Autowired
    HistoryMapper historyMapper;

    @Autowired
    CommentResearchMapper commentResearchMapper;

    @Autowired
    ResearchActiveDataMapper researchActiveDataMapper;

    /**
     * 添加研究院帖子
     *
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult saveResearch(ResearchModel researchModel) throws Exception {
        //获取用户信息
        NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(researchModel.getUserId());
        ResearchEntity researchEntity = new ResearchEntity();
        researchEntity.setSubject(researchModel.getSubject());
        researchEntity.setProductId(researchModel.getProductId());
        researchEntity.setUserId(researchModel.getUserId());
        researchEntity.setName(njkUserEntity.getNickName());
        researchEntity.setRecoverDate(DateUtil.now());
        researchEntity.setViews(0);
        researchEntity.setRecover(0);
        researchEntity.setAppraisal("0");
        researchEntity.setCream(0);
        researchEntity.setDateStatus("0");
        researchEntity.setPraiseStatus("0");
        researchEntity.setPublish("1");
        researchEntity.setTopStatus("0");
        researchEntity.setActiveStatus("0");
        researchEntity.setClickViews(0);
        researchEntity.setShareViews(0);
        //保存图片内容
        String replace = researchModel.getContent().replace("!==!", "<br/>");
        String replace1 = replace.replace("\n", "<br/>");
        if (researchModel.getImg() != null && researchModel.getImg() != "") {
            String[] split = researchModel.getImg().split(",");
            for (String s : split) {
                replace1 += "<br/><img src=" + s + "><br/>";
            }
        }
        researchEntity.setContent("<style>img{max-width:100%;}</style><p>" + replace1 + "</p>");

        researchEntity.setCreateTime(researchEntity.getRecoverDate());
        //获取坐标
        String address = "";
        if (researchModel.getLat() != null && researchModel.getLat().length() > 4 && researchModel.getLng() != null && researchModel.getLng().length() > 4) {
            address = MapDistance.getCoordinate3(researchModel.getLng(), researchModel.getLat());
        } else {
            address = "农极客";
        }
        researchEntity.setAddress(address);
        researchMapper.insert(researchEntity);
        String inform = "";
        //*****************增加用户积分*****************
        Example example1 = new Example(UserTaskEntity.class);
        example1.createCriteria().andEqualTo("userId", researchModel.getUserId());
        List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example1);
        if (userTaskEntities != null && userTaskEntities.size() > 0) {
            UserTaskEntity userTaskEntity = userTaskEntities.get(0);
            Integer.parseInt(userTaskEntity.getResearchStatus().toString());
            Integer researchNum = Integer.parseInt(userTaskEntity.getResearchNum().toString()) + 3;

            //商品信息
            ProductEntity productEntity = researchProductMapper.selectByPrimaryKey(researchModel.getProductId());
            //判断今天是否已完成 任务
            if (researchNum <= 15) {
                CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                countCommunityEntity.setCommunityType(3);
                countCommunityEntity.setCreateTime(new Date());
                countCommunityEntity.setUserId(researchModel.getUserId());
                countCommunityEntity.setNum("3");
                countCommunityEntity.setCommunityId(researchEntity.getResearchId().toString());
                countCommunityEntity.setNews("发布" + productEntity.getProductName() + "商品研究院帖子");
                countCommunityEntity.setOrderNum("");
                countCommunityMapper.insert(countCommunityEntity);
                //增加积分
                njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 3);
                //增加总积分
                njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 3);
                communityUserMapper.updateByPrimaryKey(njkUserEntity);
                //添加用户任务
                userTaskEntity.setUserId(researchModel.getUserId());
                userTaskEntity.setResearchNum(researchNum);
                userTaskEntity.setResearchStatus(1);
                userTaskMapperr.updateByPrimaryKey(userTaskEntity);
                //添加单个任务
                UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                userTaskCountEntity.setUserId(researchModel.getUserId());
                userTaskCountEntity.setTaskType(4);
                userTaskCountEntity.setCreateTime(new Date());
                userTaskCountMapper.insert(userTaskCountEntity);
                inform = "3";
            }
        }
        //保存到图片表
        ResearchImgEntity researchImgEntity = new ResearchImgEntity();
        if (researchModel.getImg() != null && !"".equals(researchModel.getImg()) && researchModel.getImg() != "") {
            String[] imgs = researchModel.getImg().split(",");
            List<String> strings = Arrays.asList(imgs);
            for (int i = 0; i < strings.size(); i++) {
                researchImgEntity.setResearchId(researchEntity.getResearchId());
                researchImgEntity.setImg(strings.get(i));
                researchImgEntity.setOrdeBy(String.valueOf(i + 1));
                researchImgEntity.setCreateDate(DateUtil.now());
                researchImgMapper.insert(researchImgEntity);
            }
        }
        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 帖子详情
     *
     * @param researchId
     * @return
     * @throws Exception
     */
    public ResponseResult showListResearch(Integer researchId, String userId) throws Exception {
        //展示研究院帖子信息
        ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(researchId);

        //增加点击数
        if (researchEntity.getClickViews() != null && !"".equals(researchEntity.getClickViews())) {
            researchEntity.setClickViews(researchEntity.getClickViews() + 1);
            researchMapper.updateByPrimaryKey(researchEntity);
        }
        //展示对应的帖子图片信息
        Example example = new Example(ResearchImgEntity.class);
        example.createCriteria().andEqualTo("researchId", researchEntity.getResearchId());
        List<ResearchImgEntity> researchImgEntities = researchImgMapper.selectByExample(example);
        List<ResearchImgEntity> collect = researchImgEntities.stream().filter(s -> s.getOrdeBy() != "100").collect(Collectors.toList());

        //获取用户的信息
        Example example1 = new Example(NjkUserEntity.class);
        example1.createCriteria().andEqualTo("userId", researchEntity.getUserId());
        List<NjkUserEntity> njkUserEntities = communityUserMapper.selectByExample(example1);

        //获取用户扩展信息
        Example example2 = new Example(NjkUserInfoEntity.class);
        example2.createCriteria().andEqualTo("userId", researchEntity.getUserId());
        List<NjkUserInfoEntity> njkUserInfoEntities = communityUserInfoMapper.selectByExample(example2);

        //返回数据模型
        List<ResearchListModel> researchListModels = new ArrayList<>();
        ResearchListModel researchListModel = new ResearchListModel();

        //得到用户信息扩展表中用户头像
        for (NjkUserInfoEntity njkUserInfoEntity : njkUserInfoEntities) {
            String img = njkUserInfoEntity.getImg();
            researchListModel.setImg(img);
            //得到用户的名
            for (NjkUserEntity njkUserEntity : njkUserEntities) {
                String nickName = njkUserEntity.getNickName();
                researchListModel.setNickName(nickName);
            }
        }
        //点赞和数量
        PraiseResearchEntity byId = praiseResearchMapper.findById(researchId.toString(), userId);
        if (byId != null) {
            researchListModel.setZan("1");
        } else {
            researchListModel.setZan("0");
        }
        researchListModel.setResearchEntity(researchEntity);
        researchListModel.setResearchImgEntities(collect);
        //分享的url
        if (researchEntity.getActiveStatus().equals("2") || researchEntity.getActiveStatus().equals("1")) {
            researchListModel.setUrl("https://www.meitiannongzi.com/nongjike/static/jsp/activity.html?researchId=" + researchId + "&uid=" + userId);
        } else {
            researchListModel.setUrl("http://www.meitiannongzi.com/nongjike/static/jsp/Researc.html?researchId=" + researchId + "&uid=" + userId);
        }
        new Thread(new History(researchEntity.getSubject(), researchId.toString(), "3", "帖子", userId, "3", historyMapper)).start();
        researchListModels.add(researchListModel);

        return new ResponseResult(ResponseMessage.OK, researchListModels);
    }

    /**
     * @Description:商品研究社
     * @author: ZPX
     * @param:
     * @return:
     * @exception:
     * @date: 2019/7/17 17:23
     */
    public ResponseResult showResearch(String productId, String dateStatus, Integer pageNum, Integer pageSize) throws Exception {

        PageHelper.startPage(pageNum, pageSize);
        List<ResearchEntity> showResearchModels = researchMapper.showResearch(productId, dateStatus);

        for (ResearchEntity showResearchModel : showResearchModels) {
            Example example = new Example(ResearchImgEntity.class);
            example.createCriteria().andEqualTo("researchId", showResearchModel.getResearchId());
            List<ResearchImgEntity> list = researchImgMapper.selectByExample(example);
            showResearchModel.setResearchImgEntities(list);
        }
        PageInfo pageInfo = new PageInfo<>(showResearchModels);
        return new ResponseResult(ResponseMessage.OK, pageInfo);
    }

    /**
     * 研究社置顶数据
     */
    public ResponseResult topResearch(String productId) throws Exception {
        List<ResearchEntity> researchEntities = researchMapper.topResearch(productId);
        return new ResponseResult(ResponseMessage.OK, researchEntities);
    }

    /**
     * 研究院点赞
     *
     * @param researchId
     * @param userId
     * @return
     */
    @Transactional
    public ResponseResult praiseResearch(Integer researchId, String userId) throws Exception {
        ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(researchId);
        //封装结果集
        Map map = new HashMap<>();

        //查询是否有该用户对该文章的点赞记录
        Example example = new Example(PraiseResearchEntity.class);
        example.createCriteria().andEqualTo("researchId", researchId)
                .andEqualTo("userId", userId);
        List<PraiseResearchEntity> praiseResearchEntities = praiseResearchMapper.selectByExample(example);
        if (praiseResearchEntities != null && praiseResearchEntities.size() > 0) {

            //如果找到了这条记录，则删除该记录，同时文章的点赞数减1
            PraiseResearchEntity praiseResearchEntity = praiseResearchEntities.get(0);
            praiseResearchEntity.getResearchId();
            praiseResearchEntity.getUserId();

            //删除记录
            praiseResearchMapper.deletePraiseResearch(praiseResearchEntity);

            //文章点赞数减1，查询时使用Mysql行级锁解决并发覆盖问题
            if (researchEntity.getViews() > 0) {
                researchEntity.setViews(researchEntity.getViews() - 1);
                researchEntity.setPraiseStatus("0");
                researchMapper.updateByPrimaryKey(researchEntity);
            }
        } else {
            PraiseResearchEntity praiseResearchEntity = new PraiseResearchEntity();
            //如果没有找到这条记录，则添加这条记录，同时文章点赞数加1
            praiseResearchEntity.setResearchId(researchId.toString());
            praiseResearchEntity.setUserId(userId);
            //添加记录
            praiseResearchMapper.insert(praiseResearchEntity);
            //文章点赞数加1，查询时使用Mysql行级锁解决并发覆盖问题
            researchEntity.setViews(researchEntity.getViews() + 1);
            researchEntity.setPraiseStatus("1");
            researchMapper.updateByPrimaryKey(researchEntity);
        }
        map.put("praiseStatus", researchEntity.getPraiseStatus());
        map.put("views", researchEntity.getViews());
        return new ResponseResult(ResponseMessage.OK, map);
    }

    /**
     * 是否置顶
     *
     * @param researchId
     * @return
     */
    @Transactional
    public ResponseResult updateTopStatus(Integer researchId) {
        ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(researchId);
        if (researchEntity != null) {
            researchEntity.setTopStatus(researchEntity.getTopStatus().equals("0") ? "1" : "0");
            researchMapper.updateByPrimaryKey(researchEntity);
        }
        return new ResponseResult(ResponseMessage.OK, researchEntity.getTopStatus());
    }

    /**
     * app分享增加用户积分
     * shareId:分享那个文章传那个ID
     */
    @Transactional
    public ResponseResult shareIntegral(String status, String shareId, String userId, String news) throws Exception {
        //获取用户表
        String inform = "";
        //获取任务表
        Example example = new Example(UserTaskEntity.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<UserTaskEntity> userTaskEntities = userTaskMapperr.selectByExample(example);
        //获取研究社数据增加分享数
        if ("1".equals(status)) {
            ResearchEntity researchEntity = researchMapper.selectByPrimaryKey(shareId);
            if ("1".equals(researchEntity.getOperatingStatus())){
                ResearchActiveDataEntity researchActiveDataEntity = new ResearchActiveDataEntity();
                researchActiveDataEntity.setCreateDate(new Date());
                researchActiveDataEntity.setActiveType(5);
                researchActiveDataEntity.setActiveId(shareId);
                researchActiveDataMapper.insert(researchActiveDataEntity);
            }
            if (researchEntity != null) {
                Integer shareViews = researchEntity.getShareViews();
                researchEntity.getResearchId();
                researchEntity.setShareViews(shareViews + 1);
                researchEntity.setShareTime(DateUtil.date());
                researchMapper.updateByPrimaryKey(researchEntity);
                if (userTaskEntities != null && userTaskEntities.size() > 0) {
                    for (UserTaskEntity e : userTaskEntities) {
                        Integer ShareNum = Integer.parseInt(e.getShareNum().toString()) + 3;

                        //判断今天是否以完成任务
                        if (ShareNum <= 15) {
                            NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
                            //获取统计表
                            CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                            countCommunityEntity.setCommunityType(5);
                            countCommunityEntity.setCreateTime(DateUtil.date());
                            countCommunityEntity.setUserId(userId);
                            countCommunityEntity.setNum("3");
                            countCommunityEntity.setCommunityId(shareId);
                            countCommunityEntity.setAudit(0);
                            if (news != null && news != "") {
                                countCommunityEntity.setNews(news);
                            }
                            countCommunityEntity.setOrderNum("");
                            countCommunityMapper.insert(countCommunityEntity);
                            //增加积分
                            njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 3);
                            //增加总积分
                            njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 3);
                            communityUserMapper.updateByPrimaryKey(njkUserEntity);
                            //添加用户任务
                            e.setUserId(userId);
                            e.setShareNum(ShareNum);
                            e.setShareStatus(1);
                            userTaskMapperr.updateByPrimaryKey(e);
                            //添加单个任务
                            UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                            userTaskCountEntity.setUserId(userId);
                            userTaskCountEntity.setTaskType(5);
                            userTaskCountEntity.setCreateTime(DateUtil.date());
                            userTaskCountMapper.insert(userTaskCountEntity);

                            inform = "3";
                        }
                    }
                }
            }
        }

        if ("0".equals(status)) {
            //获取提问数据增加分享数
            AskEntity askEntity = askMapper.selectByPrimaryKey(shareId);
            if (askEntity != null) {
                Integer shareViews = askEntity.getShareViews();
                askEntity.getAskId();
                askEntity.setShareViews(shareViews + 1);
                askEntity.setShareTime(DateUtil.date());
                askMapper.updateByPrimaryKey(askEntity);
                if (userTaskEntities != null && userTaskEntities.size() > 0) {
                    for (UserTaskEntity e : userTaskEntities) {
                        Integer ShareNum = Integer.parseInt(e.getShareNum().toString()) + 3;

                        //判断今天是否以完成任务
                        if (ShareNum <= 15) {
                            NjkUserEntity njkUserEntity = communityUserMapper.selectByPrimaryKey(userId);
                            //获取统计表
                            CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                            countCommunityEntity.setCommunityType(13);
                            countCommunityEntity.setCreateTime(DateUtil.date());
                            countCommunityEntity.setUserId(userId);
                            countCommunityEntity.setNum("3");
                            countCommunityEntity.setCommunityId(shareId);
                            countCommunityEntity.setAudit(0);
                            if (news != null && news != "") {
                                countCommunityEntity.setNews(news);
                            }
                            countCommunityEntity.setOrderNum("");
                            countCommunityMapper.insert(countCommunityEntity);
                            //增加积分
                            njkUserEntity.setIntegral(njkUserEntity.getIntegral() + 3);
                            //增加总积分
                            njkUserEntity.setTotalIntegral(njkUserEntity.getTotalIntegral() + 3);
                            communityUserMapper.updateByPrimaryKey(njkUserEntity);
                            //添加用户任务
                            e.setUserId(userId);
                            e.setShareNum(ShareNum);
                            e.setShareStatus(1);
                            userTaskMapperr.updateByPrimaryKey(e);
                            //添加单个任务
                            UserTaskCountEntity userTaskCountEntity = new UserTaskCountEntity();
                            userTaskCountEntity.setUserId(userId);
                            userTaskCountEntity.setTaskType(5);
                            userTaskCountEntity.setCreateTime(DateUtil.date());
                            userTaskCountMapper.insert(userTaskCountEntity);

                            inform = "3";
                        }
                    }
                }
            }
        }
        return new ResponseResult(ResponseMessage.OK, inform);
    }

    /**
     * 研究社活动运营数据统计
     * @param researchId
     * @param activeType 0活动弹窗打开 1网页 2活动GIF 3商城活动帖子轮播图,4社区活动帖子轮播图 5活动分享 6活动弹窗关闭
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult researchActive(String researchId,Integer activeType)throws Exception{
        ResearchActiveDataEntity researchActiveDataEntity = new ResearchActiveDataEntity();
        researchActiveDataEntity.setActiveId(researchId);
        researchActiveDataEntity.setActiveType(activeType);
        researchActiveDataEntity.setCreateDate(new Date());
        researchActiveDataMapper.insert(researchActiveDataEntity);
        return new ResponseResult(ResponseMessage.OK);
    }
}
